package com.barnett.tool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;

/**
 * assets中搜索apk安装辅助类
 * 
 * @author JiangJian
 * @version: V1.0
 */
public class ApkInstall {
	Context context;

	String fileName;
	String cachePath;

	/**
	 * 构造器
	 */
	public ApkInstall(Context context, String fileName) {
		// TODO Auto-generated constructor stub
		this.context = context;
		this.fileName = fileName;
		cachePath = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ File.separator + fileName;
	}

	/**
	 * 是否apk已安装 true为安装，直接跳转扫描界面，否则进行安装
	 */
	public void apkinstall() {
		if (!isMobile_spExist()) {
			if (copyApkFromAssets(context, fileName, cachePath)) {
				new AlertDialog.Builder(context)
						.setMessage("是否安装扫描软件（安装后方能扫描）？")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

										Intent intent = new Intent(
												Intent.ACTION_VIEW);
										intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										intent.setDataAndType(Uri
												.parse("file://" + cachePath),
												"application/vnd.android.package-archive");
										context.startActivity(intent);
									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub
										dialog.dismiss();
									}
								}).show();

			}
		} else {
			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
			((Activity) context).startActivityForResult(intent, 0x278);
		}
	}

	/**
	 * 从asset文件中读取apk文件
	 */
	public boolean copyApkFromAssets(Context context, String fileName,
			String path) {
		boolean copyIsFinish = false;
		try {
			InputStream is = context.getAssets().open(fileName);
			File file = new File(path);
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] temp = new byte[1024];
			int i = 0;
			while ((i = is.read(temp)) > 0) {
				fos.write(temp, 0, i);
			}
			fos.close();
			is.close();
			copyIsFinish = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return copyIsFinish;
	}

	/**
	 * 从当前的安装目录中查找是否存在这个apk
	 */
	public boolean isMobile_spExist() {
		PackageManager manager = context.getPackageManager();
		List<PackageInfo> pkgList = manager.getInstalledPackages(0);
		for (int i = 0; i < pkgList.size(); i++) {
			PackageInfo pI = pkgList.get(i);
			if (pI.packageName
					.equalsIgnoreCase("com.google.zxing.client.android"))
				return true;
		}
		return false;
	}
}
